import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/common/routers/router_names.dart';
import 'package:awak/common/utils/util_dialog.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/utils/util_toast.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/repository/user_repository.dart';
import 'package:awak/common/repository/content_repository.dart';
import 'package:awak/common/repository/favorite_repository.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final ContentRepository _contentRepository = ContentRepository();
  final FavoriteRepository _favoriteRepository = FavoriteRepository();
  int _userContentCount = 0;
  int _userFavoriteCount = 0;
  int _friendsCount = 0;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadUserContentCount();
  }

  Future<void> _loadUserContentCount() async {
    try {
      final userRepository = UserRepository();
      final currentUser = userRepository.currentUser;

      if (currentUser?.id != null) {
        // 获取用户发布的内容数量
        final contents = await _contentRepository.getContentsByUserId(
          currentUser!.id!,
        );
        // 获取用户收藏的内容数量
        final favorites = await _favoriteRepository.getFavoritesByUserId(
          currentUser.id!,
        );
        // 获取好友数量
        final friendsCount = await context
            .read<AwakBloc>()
            .friendshipRepository
            .getFriendsCount(currentUser.id!);

        if (!mounted) return;

        setState(() {
          _userContentCount = contents.length;
          _userFavoriteCount = favorites.length;
          _friendsCount = friendsCount;
          _isLoading = false;
        });
      } else {
        setState(() {
          _userContentCount = 0;
          _userFavoriteCount = 0;
          _friendsCount = 0;
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _userContentCount = 0;
        _userFavoriteCount = 0;
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (context) {
          // 直接从 UserRepository 获取当前用户信息
          final userRepository = UserRepository();
          final currentUser = userRepository.currentUser;

          // 用户信息
          String nickname = currentUser?.nickname ?? 'Guest';
          String signature = currentUser?.signature ?? 'No signature';
          String avatarPath = currentUser?.avatar ?? AwakImages.avatar;

          return _buildProfileUI(context, nickname, signature, avatarPath);
        },
      ),
    );
  }

  Widget _buildProfileUI(
    BuildContext context,
    String nickname,
    String signature,
    String avatarPath,
  ) {
    return Column(
      children: [
        SizedBox(
          width: double.infinity,
          child: Image.asset(AwakImages.profileBg, fit: BoxFit.contain),
        ),
        // 内容区
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Container(
                      child: _buildProfileContent(
                        context,
                        nickname,
                        signature,
                        avatarPath,
                      ),
                    ),
                    Positioned(
                      top: -25.h,
                      left: 28.w,
                      child: Stack(
                        children: [
                          Container(
                            width: 90.w,
                            height: 90.h,
                            decoration: BoxDecoration(
                              color: Colors.transparent,
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: Colors.black,
                                width: 4.w,
                              ),
                              image: DecorationImage(
                                image: AssetImage(avatarPath),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          Positioned(
                            bottom: 5.w,
                            right: 33.w,
                            child: GestureDetector(
                              onTap: () {
                                Beamer.of(
                                  context,
                                ).beamToNamed(RouterNames.editProfile);
                              },
                              child: Container(
                                width: 20.w,
                                height: 20.h,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(15.r),
                                ),
                                child: Icon(
                                  AwakSvg.edit,
                                  size: 12.w,
                                  color: Colors.black,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildProfileContent(
    BuildContext context,
    String nickname,
    String signature,
    String? avatarPath,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(width: 130.w),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 10.h),
                Text(
                  nickname,
                  style: AwakText.body18Style.copyWith(
                    color: Colors.black,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                SizedBox(height: 5.h),
                Text(
                  signature,
                  style: AwakText.body14Style.copyWith(
                    color: Colors.black.withOpacity(0.7),
                    fontWeight: FontWeight.w500,
                    fontSize: 12.sp,
                  ),
                ),
              ],
            ),
          ],
        ),
        SizedBox(height: 20.h),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 20.h),
          margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10.r),
            border: Border.all(
              color: Colors.black.withOpacity(0.2),
              width: 1.w,
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                onTap: () {
                  Beamer.of(context).beamToNamed(RouterNames.issueProfile);
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(AwakSvg.issue, size: 28.w, color: Colors.black),
                    SizedBox(width: 8.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          _isLoading ? '...' : '$_userContentCount',
                          style: AwakText.body16Style.copyWith(
                            color: Colors.black,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        Text(
                          'Issue',
                          style: AwakText.body14Style.copyWith(
                            color: Colors.black.withOpacity(0.7),
                            fontWeight: FontWeight.w500,
                            fontSize: 12.sp,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              GestureDetector(
                onTap: () {
                  Beamer.of(context).beamToNamed(RouterNames.messageProfile);
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(AwakSvg.fans, size: 28.w, color: Colors.black),
                    SizedBox(width: 8.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '$_friendsCount',
                          style: AwakText.body16Style.copyWith(
                            color: Colors.black,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        Text(
                          'Friends',
                          style: AwakText.body14Style.copyWith(
                            color: Colors.black.withOpacity(0.7),
                            fontWeight: FontWeight.w500,
                            fontSize: 12.sp,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              GestureDetector(
                onTap: () {
                  Beamer.of(context).beamToNamed(RouterNames.collectProfile);
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(AwakSvg.collect, size: 28.w, color: Colors.black),
                    SizedBox(width: 8.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          _isLoading ? '...' : '$_userFavoriteCount',
                          style: AwakText.body16Style.copyWith(
                            color: Colors.black,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        Text(
                          'Collect',
                          style: AwakText.body14Style.copyWith(
                            color: Colors.black.withOpacity(0.7),
                            fontWeight: FontWeight.w500,
                            fontSize: 12.sp,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 10.h),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
          margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
          decoration: BoxDecoration(color: Colors.transparent),
          child: Row(
            children: [
              Icon(AwakSvg.clear, size: 24.w, color: Colors.black),
              SizedBox(width: 8.w),
              Text(
                'Clear Cache',
                style: AwakText.body16Style.copyWith(
                  color: Colors.black,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Spacer(),
              Icon(Icons.arrow_forward_ios, size: 16.w, color: Colors.grey),
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 18.w),
          child: Divider(color: Colors.black.withOpacity(0.2), height: 1.w),
        ),
        SizedBox(height: 10.h),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
          margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
          decoration: BoxDecoration(color: Colors.transparent),
          child: Row(
            children: [
              Icon(AwakSvg.privacy, size: 24.w, color: Colors.black),
              SizedBox(width: 8.w),
              Text(
                'Privacy Policy',
                style: AwakText.body16Style.copyWith(
                  color: Colors.black,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Spacer(),
              Icon(Icons.arrow_forward_ios, size: 16.w, color: Colors.grey),
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 18.w),
          child: Divider(color: Colors.black.withOpacity(0.2), height: 1.w),
        ),
        SizedBox(height: 10.h),
        GestureDetector(
          onTap: () {
            showAwakDialog(
              context: context,
              title: 'LOG OUT',
              description: 'Are you sure you want to log out?',
              onCancel: () {},
              onConfirm: () {
                // 退出登录
                context.read<AwakBloc>().add(LogoutEvent());
                Beamer.of(context).beamToNamed(RouterNames.login);
                AwakToast.showCustomToast(context, 'Log out successfully!');
              },
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
            margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
            decoration: BoxDecoration(color: Colors.transparent),
            child: Row(
              children: [
                Icon(AwakSvg.logout, size: 24.w, color: Colors.black),
                SizedBox(width: 8.w),
                Text(
                  'Log Out',
                  style: AwakText.body16Style.copyWith(
                    color: Colors.black,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Spacer(),
                Icon(Icons.arrow_forward_ios, size: 16.w, color: Colors.grey),
              ],
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 18.w),
          child: Divider(color: Colors.black.withOpacity(0.2), height: 1.w),
        ),
        SizedBox(height: 10.h),
        GestureDetector(
          onTap: () {
            showAwakDialog(
              context: context,
              title: 'DELETE ACCOUNT',
              description: 'Are you sure you want to delete your account?',
              onCancel: () {},
              onConfirm: () {
                // 删除用户
                context.read<AwakBloc>().add(DeleteUserEvent());
                Beamer.of(context).beamToNamed(RouterNames.login);
                AwakToast.showCustomToast(
                  context,
                  'Delete account successfully!',
                );
              },
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
            margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
            decoration: BoxDecoration(color: Colors.transparent),
            child: Row(
              children: [
                Icon(AwakSvg.delete, size: 24.w, color: Colors.black),
                SizedBox(width: 8.w),
                Text(
                  'Delete Account',
                  style: AwakText.body16Style.copyWith(
                    color: Colors.black,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Spacer(),
                Icon(Icons.arrow_forward_ios, size: 16.w, color: Colors.grey),
              ],
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 18.w),
          child: Divider(color: Colors.black.withOpacity(0.2), height: 1.w),
        ),
      ],
    );
  }
}
